package com.digitalchina.trade.service.impl;

import com.digitalchina.trade.entity.AccountBank;
import com.digitalchina.trade.entity.TbBankCard;
import com.digitalchina.trade.mapper.AccountBankMapper;
import com.digitalchina.trade.mapper.BankCardMapper;
import com.digitalchina.trade.service.BankCardService;
import com.digitalchina.trade.utils.MailUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.mail.MessagingException;
import java.util.List;
import java.util.Random;

@Service
public class BankCardServiceImpl implements BankCardService {
    @Autowired
    BankCardMapper bankCardMapper;
    @Autowired
    AccountBankMapper acBankMapper;
    @Autowired
    AccountBank acBank;

    @Override
    public Boolean bindingCard(int accountId, TbBankCard bankCard) {
        //查找库种对应银行卡信息
        TbBankCard findCard = bankCardMapper.findByNum(bankCard.getBandcard_num());
        //信息校验
        if (findCard.getBankcard_IDcard() .equals( bankCard.getBankcard_IDcard()) && findCard.getBankcard_name().equals(bankCard.getBankcard_name()) ) {
            //是否已经绑定
            List<TbBankCard> list = acBankMapper.findByUser(accountId);
            for (TbBankCard temp : list) {
                if (temp.getBandcard_num().equals(bankCard.getBandcard_num()) ) {
                    return false;
                }
            }
            acBank.setR_bankcard(findCard.getBankcard_id());
            acBank.setR_account(accountId);
            acBankMapper.saveBinding(acBank);
            return true;
        }
        return false;
    }

    @Override
    public String sendMail(String bankCardNum) {
        TbBankCard bankCard = bankCardMapper.findByNum(bankCardNum);
        //产生六位随机数
        Random random = new Random();
        String key = "";
        for (int i = 0; i < 6; i++) {
            key += random.nextInt(10);
        }
        try {
            MailUtils.sendMail(bankCard.getBankcard_email(), "电子账务系统邮件验证码", key);
        } catch (MessagingException e) {
            e.printStackTrace();
        }
        return key;
    }

    public List<TbBankCard> findCards(int account) {
        List<TbBankCard> cardList = acBankMapper.findByUser(account);
        //去除隐私数据
        for (TbBankCard temp : cardList) {
            temp.setBandcard_pwd("");
            temp.setBankcard_id(0);
            temp.setBankcard_IDcard("");
        }
        return cardList;
    }
}
